<?php
/**
 * Created by tiyangwu.
 * User: tiyangwu <tiyangwu@37degree.com>
 * Date: 2016/2/22
 * Time: 0:19
 */
namespace Home\Controller;
use Think\Controller;
/**
 * Class LoginController
 * @package Home\Controller
 */
class MemberController extends CommonController {
    public static $activate_title = '【 云途数据】帐号激活';//邮件激活title
    public static $activate_name = '尊敬的云途用户';//邮件用户昵称
    public static $acivate_expir = 24;//激活有效期（单位：小时）
    //private $activate_key = "@37Degree#2016";//激活链接，密钥
    
    public static $resetpwd_title = '【 云途数据】找回密码';//邮件激活title
    
    public function __construct(){
        parent::__construct();
    }

    public function __call($function_name, $args){
        if(IS_POST){
            echo json_encode(array());die;
        }elseif( file_exists_case($this->view->parseTemplate()) ){
            $this->display();
        }else{
            $this->error('链接无效');
        }
        
    }

    /**
     * 用户登录
     */
    public function login()
    {
        $this->checkLogin();
        if($this->role==1){
            redirect('/user/index');
            //$this->ajaxReturn(array('status'=>200,"msg"=>'',"data"=>'1'));
        }else if($this->role==2){
            redirect('/apiworks/index');
            //$this->ajaxReturn(array('status'=>200,"msg"=>'',"data"=>'2'));
        }
        
        if (IS_POST) {
            $login_type = I('post._login_type');//登录页面
        	//判断
        	if( empty (I('post.user_email','','htmlspecialchars'))){
                $this->ajaxReturn(array('status'=>1,"msg"=>'请填写邮箱',"data"=>null));
        	}
        	if(empty (I('post.passwd')) ){
                $this->ajaxReturn(array('status'=>2,"msg"=>'请填写密码',"data"=>null));
        	}
					
            // 验证码是否正确
           // $verify = $this->checkVerify($_POST['geetest_challenge'],$_POST['geetest_validate'], $_POST['geetest_seccode']);
        
           //  if($verify==false){
           //      $this->ajaxReturn(array('status'=>3,"msg"=>'验证码错误',"data"=>null));
           //  }

            //新版验证码
            $code = I('post.verify');
            $verify = $this->_checkImgverify($code);
             if($verify==false){
                $this->ajaxReturn(array('status'=>3,"msg"=>'验证码错误',"data"=>null));
            }

        	//查询
        	$User = M('Users');
        	$where['user_email'] = trim(I('post.user_email'));
            $user_type = I('post.37degree_role');
            if(!in_array($user_type,array('2','1'))){
            	$this->ajaxReturn(array('status'=>1,"msg"=>'请选择用户身份',"data"=>null));
            }
            // $where['user_type'] = $user_type;    //不限制账号
            
            $result = $User->where($where)->field('*')->find();
        	//验证密码
            if(!empty($result)){
            	if($result['user_passwd'] == md5( trim(I('post.passwd')) )){
            		 if($result['user_status']!=1){
                         $this->ajaxReturn(array('status'=>1,"msg"=>'邮箱未激活',"data"=>null));
                     }
                     //存储session
                     session('nickname',$result['user_email']);
                     switch($result['user_type']){
                         case 1:
                             $tag = C('37DEGREE_HOME_TAG')."-".$result['user_email'];
                             break;
                         case 2:
                             $tag = C('37DEGREE_SERVER_TAG')."-".$result['user_email'];
                             break;
                         default:
                             $tag = null;
                     }
                     session('uid',$result['id']);
                     session('37degree_auth_status',$result['user_auth_status']);//认证状态
                     session('user_email',$result['user_email']);//登录邮箱
                     session('auth_type',$result['auth_type']);//认证类型(企业或个人认证)
                     session('user_token',$result['user_token']);//用户token信息

                     session('37degree_tag','' );//先清除掉标记

                     session('37degree_tag',myEncrption($tag) );
                     session('user_auth_fail',$result['auth_fail_cause']);//认证失败原因

                     //如果已经认证，session中记录认证后用户名或者企业编号
                     session('enterprise_id',$result['enterprise_id']);
                     // session('user_name',$result['user_name']);
                     
                     //认证用户，获取用户手机号
                     if($result['user_auth_status']==2){
                        if($result['auth_type']==1){//个人认证
                            session('user_tel',$result['user_mobile']);
                            session('user_name',$result['user_name']);
                        }else{//企业认证
                            $enterpriseModel = M('Enterprises');
                            $enterprise_where['id'] = $result['enterprise_id'];
                            $enterprise_info = $enterpriseModel->field('contacts_mobile,enterprise_name')->where($enterprise_where)->find();
                            if(!empty($enterprise_info)){
                                session('user_tel',$enterprise_info['contacts_mobile']);
                                session('user_name',$enterprise_info['enterprise_name']);
                            }else{
                                session('user_tel',null);
                            }
                        }
                     }
                     // $this->ajaxReturn(array('status'=>200,"msg"=>'',"data"=>$result['user_type']));
                     $this->ajaxReturn(array('status'=>200,"msg"=>'',"data"=>1));
            	}else{
            		 $this->ajaxReturn(array('status'=>2,"msg"=>'请输入正确的密码',"data"=>null));
            	}
            }else{
                $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确的邮箱',"data"=>null));
            }
            
        } else {
            $role = trim(I('get.role'));
            $role = 'user';//后期去掉企业登录页面
            
            if($role=='company'){
            	$this->assign('head_title','服务商登录－云途数据市场');
                $this->display('sign_enterprise');
            }else{
            	$this->assign('head_title','用户登录－云途数据市场');
                $this->display();    
            }
        }
    }

    //登录异常后页面转向
    private function loginRedirect($type){
        $type = 'login';//后期去掉企业登录页面
        switch ($type) {
            case 2:
                $this->display('sign_enterprise');
                break;
            default:
                $this->display('login');
                break;
        }
        return false;
    }

    //用户注册异常后页面转向
    private function registerRedirect(){
        $this->display('register');
        return false;
    }
    
    
    /**
     * 用户注册
     */
    public function register()
    {
        // 判断提交方式 做不同处理
        
        if (IS_POST) {
            //条件判断
            if(empty(I('post.pt')) || empty(I('post.email'))){
                $this->ajaxReturn(array('status'=>1,"msg"=>'请填写邮箱',"data"=>null));
            }
 
            if(empty(I('post.passwd'))){
            	$this->ajaxReturn(array('status'=>2,"msg"=>'请填写密码',"data"=>null));
            }
            
            $type = I('post.pt','us');
            switch($type){
                case 'supplier':
                    $user_type = 2;//服务发布商
                    break;
                default:
                    $user_type = 1;
            }
            $email = I('post.email');
            $passwd = I('post.passwd');

            //判断email规则
            if(!checkEmail($email) ){
                $this->ajaxReturn(array('status'=>1,"msg"=>'请填写正确的邮箱',"data"=>null));
            } 
            
            //判断密码规则
             if(!checkPasswd($passwd) ){
                 $this->ajaxReturn(array('status'=>2,"msg"=>'请输入6至16位字符',"data"=>null));
             }
            
            
            $user = M('Users');
            //email唯一性验证
            $quniue_where['user_email'] = $email;
            $user_count = $user->where($quniue_where)->count();
            if($user_count){
                $this->ajaxReturn(array('status'=>1,"msg"=>'该邮箱已存在',"data"=>null));
            } 

            //入库（没有激活）
            $data['user_email'] = trim($email);
            $data['user_passwd'] = md5($passwd);
            $data['create_time'] = time();
            $data['user_type'] = $user_type;
            $result = $user->data($data)->add();

            if($result){
                //邮件发送
                $this->sendEmailWithActivate($email);//test

                //$this->assign('send_email',$email);
                //$this->display("mailsuccess");
                $this->ajaxReturn(array('status'=>200,"msg"=>'',"data"=>$email));
            }else{
               $this->ajaxReturn(array('status'=>1,"msg"=>'系统异常',"data"=>$email));
           }
        } else {
        	$this->assign('head_title','注册－云途数据市场');
            $this->display();
        	//get请求，刷新本页面
            //$this->ajaxReturn(array('status'=>3,"msg"=>'',"data"=>null));
        }
    }

    //帐号激活
    public function activate(){
        //链接有效性
        $res = I('get.res',null,urldecode);
        $email = I('get.email',null,trim);

        if(empty($res) || empty($res)) {
            $this->assign('message','链接无效');
            $this->display('errorActivate');
            return false;
        }

        $now = time();
        $vcode_time = substr($res, 0,10);
        $vcode = substr($res,10);
        $expire_time = $now + C(REDIS_RESET_EMAIL_EXPIRE);
        
        //时效性校验
        if($vcode_time < $now || $vcode_time > $expire_time){
            $this->assign('message','该链接已失效，请重新激活');
            $this->display('errorActivate');
            return false;
        }

        //$vcode = S($email."-".C(RESET_PRIX));
        //查库校验
        $emailModel = M('EmailVcode');
        $email_where = array('email'=>$email,'type'=>1);
        $info = $emailModel->where($email_where)->find();

        if(empty($info) || $info['vcode_md5'] != $vcode || $info['expiration_time'] < $now || $info['times'] == 1){
            $this->assign('message','该链接已失效，请重新激活');
            $this->display('errorActivate');
            return false;
        }

        $user = M('Users');
        $where['user_email'] = $email;
        $user_info = $user->where($where)->find();

        if(empty($user_info)) {
            $this->assign('message','无效帐号');
            $this->display('errorActivate');
            return false;
        }
        if($user_info['user_status']==1) {
            $this->assign('message','该帐号已激活');
            $this->assign('user_type',$user_info['user_type']);
            
            $this->display('errorActivate');
            return false;
        }

        //用户激活状态改变
        $data['user_status'] = 1;
        $data['activation_time'] = time();
        //获取唯一token
        $guid = guid();
        $data['user_token'] = $guid;
        
        $result = $user->where('id='.$user_info['id'])->save($data);
        if($result){
            //更新激活码使用
            $emailModel->where($email_where)->save( array('times'=>1) );

            //根据条件更新记录
            //todo

            //大后台记录（http basic auth）//https://api.37degree.com/open/api_mgr_srv/user_add 
            $auth_data = array('user'=>$email,'pwd'=>$guid);
            $result = dmp_curl_post(C(AUTH_ADD_USER),$auth_data);
            
            if($result['status']==200){
                $this->assign('user_type',$user_info['user_type']);
                //验证成功页面
                $this->display('mail_complete');
            }
            
        }else{
            redircet('/member/login');    
        }
        
    }

    //发送激活邮件
    public function sendEmailWithActivate($email,$url_prefix = "/member/activate.html"){
        if(empty($email)) return false;

        //切换加密算法
        $time = time();
        //$url_footer = md5( sha1($string).C(GLOBAL_KEY) );
        $vcode = md5( sha1( $email."^".$time ).C(GLOBAL_KEY) );
        $expire_time = $time+C(REDIS_REGISTER_EMAIL_EXPIRE);
        $url_footer = $expire_time.$vcode;

        //激活码入库
        $emailModel = M('EmailVcode');
        $data['email'] = $email;
        $data['vcode_md5'] = $vcode;
        $data['type'] = 1;//注册
        $data['expiration_time'] = $expire_time;
        $data['times'] = 0;
        $where = array('email'=>$email,'type'=>1);
        try{
            $count = $emailModel->where($where)->count();
            if($count){
                $result = $emailModel->where($where)->save($data);
            }else{
                $result = $emailModel->data($data)->add();
            }

            //密钥有效期存放在redis中
            //S($email."-".C(REGISTER_PRIX),$url_footer,array('type'=>'Redis','expire'=>C(REDIS_REGISTER_EMAIL_EXPIRE)));

            //邮件内容
            if($result){
                $url = "http://".$_SERVER['SERVER_NAME'].$url_prefix."?res=".$url_footer."&email=".$email;
                $content = getActivationContent($url,self::$activate_name,self::$acivate_expir);

                return sendMail($email,self::$activate_title,$content);
            }

        }catch(exception $e){
            return false;
        }
        
    }
    
    
    //发送重置密码邮件
    public function sendEmailWithResetpwd($email,$url_prefix){
        if(empty($email)) return false;

        //切换加密算法
        $time = time();
        // $url_footer = encrypt($string,C(GLOBAL_KEY));
        $vcode = md5( sha1( $email."^".$time ).C(GLOBAL_KEY) );
        $expire_time = $time+C(REDIS_RESET_EMAIL_EXPIRE);
        $url_footer = $expire_time.$vcode;
        
        //激活码入库
        $emailModel = M('EmailVcode');
        $data['email'] = $email;
        $data['vcode_md5'] = $vcode;
        $data['type'] = 2;//忘记密码
        $data['expiration_time'] = $expire_time;
        $data['times'] = 0;//未使用
        $where = array('email'=>$email,'type'=>2);
        try{
            $count = $emailModel->where($where)->count();
            if($count){
                $result = $emailModel->where($where)->save($data);
            }else{
                $result = $emailModel->data($data)->add();
            }

            //密钥有效期存放在redis中
            //S($email."-".C(RESET_PRIX),$url_footer,array('type'=>'Redis','expire'=>C(REDIS_RESET_EMAIL_EXPIRE)));
        
            if($result){
                //邮件内容
                $url = "http://".$_SERVER['SERVER_NAME'].$url_prefix."?res=".$url_footer."&email=".$email;
                $content = resetPwdContent($url);

                return sendMail($email,self::$resetpwd_title,$content);
            }

        }catch(exception $e){
            return false;
        }
        
    }

    /**
     * 用户注销
     */
    public function logout()
    {
        $type = I('get.role',null);
        // 清楚所有session
        session(null);
        if(empty($type)){
            redirect('/member/login');
        }else{
            redirect('/member/login?role=company');
        }
        
    }
    
    //忘记密码
    public function getpassword(){
        if (IS_POST) {
            $email = I('post.email');
            if(empty($email)){
            	 $this->ajaxReturn(array('status'=>1,"msg"=>'请输入邮箱',"data"=>null));
            }

            if(!checkEmail($email)){
                $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确的邮箱',"data"=>null));
            }

            $userModel = M('Users');
            $where['user_email'] = $email;

            $user_info = $userModel->where($where)->find();
            if(!empty($user_info)){
                //发送邮件
                $this->sendEmailWithResetpwd($email,$url_prefix = "/member/resetpwd.html");

				//$this->assign('user_email',$email);
                //$this->display('resetmailsuccess');
                
                //发送结果页
                //$this->display('getpasswd_mail');
                
                $this->ajaxReturn(array('status'=>200,"msg"=>'',"data"=>$email));
            }else{
                $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确的邮箱',"data"=>null));
            }

        }else{
        	$this->assign('head_title','忘记密码－云途数据市场');
            $this->assign('status',1);
            $this->display();
        }

    }

    //密码重置激活
    public function  resetpwd(){
        if(IS_POST){
            $email = I('post.user_email');
            if(empty($email) || !checkEmail($email) ){
                $this->ajaxReturn(array('status'=>1001,"msg"=>'请输入正确的邮箱',"data"=>null));
            }

            //密码一致性
            $first_pwd = I('post.first_pwd');
            $second_pwd = I('post.second_pwd');
            
            if(!checkPasswd($first_pwd)){
                $this->ajaxReturn(array('status'=>1,"msg"=>'请输入6－16位字符的密码',"data"=>null));
            }
            
            if($first_pwd!=$second_pwd){
                $this->ajaxReturn(array('status'=>2,"msg"=>'请输入相同的密码',"data"=>null));
            }

            //判断邮箱是否存在
            $uModel = M();
            $sql = "select id,user_passwd from dmp_users where user_email='".$email."' and user_status>0";
            $rs = $uModel->query($sql);
            if(empty($rs)){
            	//用户不存在
            	$this->ajaxReturn(array('status'=>1001,"msg"=>'请输入正确的邮箱',"data"=>null));
            }else{
            	//如果新输入的密码和原始密码一致(不执行数据库修改，直接返回)
            	if(md5($first_pwd) == $rs[0]['user_passwd']){
            		$this->ajaxReturn(array('status'=>200,"msg"=>'',"data"=>$email));
            	}
            }

            //修改密码
            $where['user_email'] = $email;
            $userModel = M('Users');
            $data['user_passwd'] = md5($first_pwd);
            $result = $userModel->where($where)->save($data);

            //更新使用
            $emailModel = M('EmailVcode');
            $now = time();
            $email_where = array('email'=>$email,'type'=>2);
            //更新为已使用
            $emailModel->where($email_where)->save( array('times'=>1) );

            //$this->display('resetsuccess');
            if($result){
            	 $this->ajaxReturn(array('status'=>200,"msg"=>'',"data"=>$email));
            }else{
            	 $this->ajaxReturn(array('status'=>1001,"msg"=>'密码重置失败',"data"=>null));
            }

        }else{
            $res = I('get.res',null,urldecode);
            $email = I('get.email',null,trim);
            
            if(empty($res) || empty($email)){
                //$this->assign('error_msg','无效的链接');
               // $this->display('mailfail');
                redirect('/member/mailfail');
            } 
//            $this->error('链接无效1');
            
            $vcode_time = substr($res, 0,10);//有效期时间
            $now = time();
            $vcode = substr($res,10);
            $expire_time = time()+C(REDIS_RESET_EMAIL_EXPIRE);
            //时效性校验
            if($vcode_time < $now || $vcode_time > $expire_time){
                redirect('/member/mailfail');
            }

            //查库校验
            $emailModel = M('EmailVcode');
            $email_where = array('email'=>$email,'type'=>2);
            $info = $emailModel->where($email_where)->find();
            
            if(empty($info) || $info['vcode_md5'] != $vcode || $info['expiration_time'] < $now || $info['times']==1){
//                $this->assign('error_msg','链接已经失效!');
//                $this->display('mailfail');
                redirect('/member/mailfail');
            }

            $this->assign('user_email',$email);
            $this->assign('head_title','重置密码－云途数据市场');
            $this->assign('status',1);
            $this->assign('message',null);

            $this->display('getpasswd_mail');
        }

    }

    /**
     * 验证码
     */
    public function verify()
    {
        
        import('Vendor.Geelib.Gee');
        $captcha_id = C("CAPTCHA_ID");
        $private_key = C("CAPTCHA_PRIVATE_KEY");
        // echo $captcha_id."===".$private_key;die;
        $GtSdk = new \Gee($captcha_id, $private_key);
		// $user_id = "hsp2004@126.com";
		$user_id = "704819236@qq.com";
		$status = $GtSdk->pre_process($user_id);
				
		session('gtserver',$status);
		session('user_id',$user_id);
        echo $GtSdk->get_response_str();
    }

    //验证码检测
    private function checkVerify($challenge,$validate,$seccode){
        
        
        import('Vendor.Geelib.Gee');
        //session_start();
        
        $captcha_id = C("CAPTCHA_ID");
        $private_key = C("CAPTCHA_PRIVATE_KEY");

		$GtSdk = new \Gee($captcha_id, $private_key);
		
		
		$status = session("gtserver");
		$uid = session("user_id");
		if ($status == 1) {
			
			$result = $GtSdk->success_validate($challenge,$validate,$seccode,$uid);
			if ($result) {
				
			return true;
			} else{
				
			return false;
			}
		}else{
			if ($GtSdk->fail_validate($challenge,$validate,$seccode)) {
				
			return true;
			}else{
				
			return false;
			}
		}
      
    }


    //获取验证码
    public function imgverify(){
        $Verify = new \Think\Verify();
        $verify->bg = array(100,100,100);
        $Verify->fontSize = 25;
        $verify->useCurve = false;
        $Verify->length   = 4;
        $Verify->useNoise = true;
        $Verify->fontttf = '4.ttf'; 
        // $Verify->useImgBg = true;
        // $Verify->useZh = true;
        $Verify->entry();

    }

    //检测验证码
    private function _checkImgverify($code, $id = ''){
        $verify = new \Think\Verify();    
        return $verify->check($code, $id);
    }

    //代码曾获取验证码文字
    // public function testverify(){
    //     timp(session('test_tyw_code'));
    // }
}
